ScheduledThreadPoolExecutor多线程处理

您所在的位置:网站首页 scheduledthreadPool 遍历 ScheduledThreadPoolExecutor多线程处理

ScheduledThreadPoolExecutor多线程处理

2024-07-17 04:27| 来源: 网络整理| 查看: 265

1.作用

ScheduledThreadPoolExecutor用于定时任务,这里的定时意义在于:适用于多个后台线程执行周期性任务

2.ScheduledThreadPoolExecutor类

 0.先看下ScheduledThreadPoolExecutor类,继承了ThreadPoolExecutor类,实现ScheduledExecutorService类

1.创建ScheduledThreadPoolExecutor的方法如下:

corePoolSize是线程池中的核心线程数,ThreadFactory是线程

2.有以下几种方法

schedule(Runnable command, long delay, TimeUnit unit) // 无返回值的延迟任务schedule(Callable callable, long delay, TimeUnit unit) // 有返回值的延迟任务scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) // 固定频率周期任务scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) // 固定延迟周期任务

 

3.代码例子 1. scheduleAtFixedRate package com.demo; import lombok.extern.slf4j.Slf4j; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; /** * @Author:xiaxia * @Date:2021/7/27 */ @Slf4j public class ThreadTest { public static void main(String[] args){ ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); scheduledThreadPool.scheduleAtFixedRate(() -> { try { sleep(1000); // 睡眠 1s, log.info("run task"); } catch (InterruptedException e) { e.printStackTrace(); } //log.info("run task"); }, 1, 2, TimeUnit.SECONDS); } private static void sleep(int i) throws InterruptedException { Thread.sleep(1000); } }

输出如下:

 

2.schedule public class ThreadTest { public static void main(String[] args){ ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5); try { //schedule to run after sometime System.out.println("Current Time = "+getNowDate()); for(int i=0; i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3